package com.ygqh.baby.interceptor;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

public class YgExceptionHandler {

    protected final Logger logger = Logger.getLogger(this.getClass());

    /**
     * 基于@ExceptionHandler异常处理
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public JSONPObject execute(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        String callback = request.getParameter("callback");
        String methodName = request.getRequestURI();

        Map<String, String[]> parameterMap = request.getParameterMap();
        String param = JSON.toJSONString(parameterMap);
        // TODO
        StringBuilder sb = new StringBuilder();
        sb.append("【methodName】=" + methodName).append(";【param】=" + param + "</br>")
                .append("【异常类型】:" + ex.getClass().getName() + "【" + ex.getMessage() + "】</br>");
        StackTraceElement[] st = ex.getStackTrace();
        for (StackTraceElement stackTraceElement : st) {
            String exclass = stackTraceElement.getClassName();
            String method = stackTraceElement.getMethodName();
            if (exclass.contains("com.ygqh.baby")) {
                sb.append(DateConvertUtils.formatDateTime(new Date()) + ":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber()
                        + "行代码处发生异常!");
            }
        }
        ex.printStackTrace();
        logger.error(sb.toString(),ex);
        return new JSONPObject(callback, Message.error(ex.getMessage()));
    }
}
